package com.cashmama.market.api.domain.service;

import com.alibaba.fastjson.JSON;
import com.cashmama.market.api.domain.vo.user.UserAuthInfoVO;
import com.cashmama.market.api.infras.exception.ApplicationException;
import com.fqgj.common.api.Response;
import com.fqgj.xjd.user.client.UserQuotaService;
import com.fqgj.xjd.user.client.enums.UserQuotaEnum;
import com.fqgj.xjd.user.client.request.UserQuotaRequest;
import com.fqgj.xjd.user.client.response.UserQuotaResponse;
import com.qianli.cashmama.product.facade.result.Product;
import com.qianli.cashmama.trade.client.trade.TradeQueryService;
import com.qianli.cashmama.trade.client.vo.UserLevelVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

/**
 * @program: market-api
 * @description
 * @author: frank
 * @create: 2019-12-25 11:14
 **/
@Service
public class ApiUserQuotaService {

    private final static Logger LOGGER = LoggerFactory.getLogger(ApiUserQuotaService.class);

    @Autowired
    private UserQuotaService userQuotaService;

    @Autowired
    private ProductService productService;
    @Autowired
    private TradeQueryService tradeQueryService;
    @Autowired
    private ApiTradeService apiTradeService;
    @Autowired
    private ApiUserService apiUserService;

    /**
     * 获取额度
     *
     * @param userCode
     * @param productCategory
     * @return
     */
    public BigDecimal getUserQuotaAmount(String userCode, String productCategory) {
        try {
            UserQuotaResponse userQuotaResponse = userQuotaService.getQuota(userCode, productCategory).getData();
            if (userQuotaResponse.getRiskLevel() == null) {
                return null;
            }
            UserAuthInfoVO userAuthInfoVO = apiUserService.getUserAuthInfo(userCode);
            boolean isNewUser = userAuthInfoVO.isNewUser();
            Date registerDate = userAuthInfoVO.getAuthDate();
            Integer riskLevel = userQuotaResponse.getRiskLevel();
            Product product = productService.getProductByCategoryCodeAndLevel(productCategory, riskLevel, isNewUser, registerDate);
            return new BigDecimal(product.getPrincipalMoney()).setScale(2, BigDecimal.ROUND_HALF_UP);
        } catch (Exception e) {
            LOGGER.error("获取额度失败1,userCode:{},productCategory:{}", userCode, productCategory, e);
            throw new ApplicationException("Evaluate Quota error");
        }
    }

    /**
     * 获取额度
     *
     * @param userCode
     * @param productCategory
     * @return
     */
    public UserQuotaResponse getUserQuota(String userCode, String productCategory) {
        try {
            UserQuotaResponse userQuotaResponse = userQuotaService.getQuota(userCode, productCategory).getData();
            if (userQuotaResponse.getRiskLevel() == null) {
                return userQuotaResponse;
            }
            Integer riskLevel = userQuotaResponse.getRiskLevel();
            UserAuthInfoVO userAuthInfoVO = apiUserService.getUserAuthInfo(userCode);
            boolean isNewUser = userAuthInfoVO.isNewUser();
            Date registerDate = userAuthInfoVO.getAuthDate();
            Product product = productService.getProductByCategoryCodeAndLevel(productCategory, riskLevel, isNewUser, registerDate);
            BigDecimal userQuotaAmount = new BigDecimal(product.getPrincipalMoney()).setScale(2, BigDecimal.ROUND_HALF_UP);
            userQuotaResponse.setQuota(userQuotaAmount.doubleValue());
            return userQuotaResponse;
        } catch (Exception e) {
            LOGGER.error("获取额度失败2,userCode:{},productCategory:{}", userCode, productCategory, e);
            throw new ApplicationException("Query Quota error");
        }
    }

    public void evaluateQuota(String userCode, String categoryCode) {
        Response<UserQuotaResponse> userExistQuota = userQuotaService.getQuota(userCode, categoryCode);

        Integer defaultUserLevel = userExistQuota.getData().getRiskLevel();
        Integer userLevel = defaultUserLevel;

        try {
            Response<UserLevelVO> userLevelVOResponse = tradeQueryService.getUserLevel(userCode, categoryCode, userLevel, "");
            userLevel = userLevelVOResponse.getData().getLevel();
            LOGGER.info("============trade 额度评估 获取额度成功==========userCode:{},quota:{}", userCode, JSON.toJSONString(userLevelVOResponse));
        } catch (Exception e) {
            LOGGER.error("== 评估额度接口异常 ==,userCode:{},categoryCode:{}", userCode, categoryCode, e);
        }

        LOGGER.info("============额度评估 获取额度成功==========userCode:{},userLevel:{}", userCode, userLevel);
        //根据用户级别 获取最大产品额度
        UserQuotaRequest userQuotaRequest = new UserQuotaRequest();
        if (userLevel == -1) {
            userQuotaRequest.setAmount(0D);
        } else {
            UserAuthInfoVO userAuthInfoVO = apiUserService.getUserAuthInfo(userCode);
            boolean isNewUser = userAuthInfoVO.isNewUser();
            Date registerDate = userAuthInfoVO.getAuthDate();

            Product product = productService.getProductByCategoryCodeAndLevel(categoryCode, userLevel, isNewUser, registerDate);
            if (product == null) {
                product = productService.getProductByCategoryCodeAndLevel(categoryCode, defaultUserLevel, isNewUser, registerDate);
            }
            userQuotaRequest.setAmount(Double.valueOf(product.getPrincipalMoney()));
        }
        userQuotaRequest.setCategoryCode(categoryCode);
        userQuotaRequest.setUserCode(userCode);
        userQuotaRequest.setQuotaEnum(UserQuotaEnum.PASS);
        userQuotaRequest.setRiskLevel(userLevel);
        userQuotaRequest.setDealNo("");
        Response<Boolean> response = userQuotaService.saveQuotaResult(userQuotaRequest);
        LOGGER.info("调用user的 userQuotaService evaluateQuota 接口，入参：userCode{},categoryCode{},response:{}",
                userCode, categoryCode, JSON.toJSON(response));
    }
}
